package jmx.demo.client;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import jmx.demo.mbean.HelloWorldMBean;

public class HelloWorldClient {

	public static void main(String[] args) throws IOException, MalformedObjectNameException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, InvalidAttributeValueException {
		echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server"); 
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1089/testJMXServer");
		JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
		
		echo("\nGet an MBeanServerConnection");	
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		
		echo("\nDomains:");
		String domains[] = mbsc.getDomains();
		for (int i = 0; i < domains.length; i++) {
			echo("\tDomain[" + i + "] = " + domains[i]);  
		}  
			
		echo("\nMBean count = " + mbsc.getMBeanCount());
		Set<ObjectName> names = mbsc.queryNames(null, null);
		for(Iterator<ObjectName> iterator = names.iterator(); iterator.hasNext();) {
			echo("\tObjectName = " + (ObjectName) iterator.next());  
		}
		ObjectName helloObjName = new ObjectName("testJMXServer:name=HelloWorld");
		// Access MBean   
        // Get attribute in MBean  
        echo("\nName = " + mbsc.getAttribute(helloObjName, "Name"));
        //set attribute value in MBean
        mbsc.setAttribute(helloObjName, new Attribute("Name", "测试name"));
        // invoke the MBean's method
        mbsc.invoke(helloObjName, "printHello", null, null);
        mbsc.invoke(helloObjName, "printHello", new Object[] {"testetstetst"}, new String[] {String.class.getName()});
        
        // Proxy way to access MBean 
        HelloWorldMBean proxy = MBeanServerInvocationHandler.newProxyInstance(mbsc, helloObjName, HelloWorldMBean.class, false);
        echo(proxy.getName());  
        proxy.setName("帅哥一个");     
        echo(proxy.getName());  
        proxy.printHello(); 
        echo("/nClose the connection to the server");  
        jmxc.close();  
        echo("/nBye! Bye!");  
	} 	
	
	private static void echo(String msg) {
		System.out.println(msg);
	}
}
